<?php
	class DAO {
		
		protected $_db;
		protected $_rs;
		protected $_last_insert_id;
		protected $_error;
		
		public function __construct() {
			$this->_db = Database::getInstance();
			$this->_rs = $this->_last_insert_id = $this->_error = NULL;
		}
		
		public function query($sql) {
			$conn = $this->_db->getConnection();
			$this->_rs = $conn->query($sql);
			if($conn->errno) {
				$this->_error = "Database Error { ERRNO: {$conn->errno}, MSG: {$conn->error} }";
			}
		}
		
		public function queryOK() {
			return (!$this->hasError() && $this->_rs->num_rows);
		}
		
		public function insertOK() {
			// MySQLi returns TRUE for succcesful INSERT, FALSE otherwise
			if($this->_rs === true) {
				$this->_last_insert_id = $this->_db->getConnection()->insert_id;
				return true;
			} else return false;
		}
		
		public function updateOK() {
			return ($this->_db->getConnection()->affected_rows >= 0);
		}
		
		public function next($associative = true) {
			if($associative) {
				return $this->_rs->fetch_assoc();
			} else return $this->_rs->fetch_row();
		}
		
		public function getEscapedSQLString($text) {
			return $this->_db->getConnection()->real_escape_string($text);
		}
		
		public function getInsertId() {
			return $this->_last_insert_id;
		}
		
		public function hasError() {
			return !is_null($this->_error);
		}
		
		public function getError() {
			return $this->_error;
		}
		
	}